package com.tensquare.friend.service;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.dao.FriendDao;
import com.tensquare.friend.dao.NoFriendDao;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class FriendService {
   @Autowired
   private FriendDao friendDao;
   @Autowired
   private NoFriendDao nofriendDao;

   @Autowired
   private UserClient userClient;

   //添加好友
   public void addFriend(String userId,String friendId){

     if (friendDao.getCountByUserIdAndFriendId(userId, friendId)>0){ //已经添加好友
         throw new RuntimeException("请勿重复添加");
     }

      //创建Friend对象
      Friend friend = new Friend();
      friend.setUserid(userId);
      friend.setFriendid(friendId);
      friend.setIslike("0");//单向喜欢
      //调用Dao保存
      friendDao.save(friend);
      //判断是否为双向喜欢
      Long count = friendDao.getCountByUserIdAndFriendId(friendId, userId);
      if(count > 0){ // 双向喜欢
         friendDao.updateIsLike(userId,friendId,"1");
         friendDao.updateIsLike(friendId,userId,"1");
      }

      //远程调用 => 维护用户表的粉丝|关注数量
      Result result1 = userClient.changeFollowCount(userId, 1);
      Result result2 = userClient.changeFansCount(friendId,1);

      if (!result1.isFlag() || !result2.isFlag()) { //两个微服务其中一个或全部调用失败
         throw new RuntimeException("操作失败!");
      }
   }
   //添加非好友
   public void addNoFriend(String userId,String friendId){
      NoFriend nofriend = new NoFriend();
      nofriend.setUserid(userId);
      nofriend.setFriendid(friendId);

      nofriendDao.save(nofriend);
   }

   //删除好友
   public void delFriend(String userId,String friendId){
      //删除Friend表记录
      friendDao.deleteByUserIdAndFriendId(userId,friendId);
      //修改另一方的isLike属性为0
      friendDao.updateIsLike(friendId,userId,"0");
      //向noFriend表添加记录
      this.addNoFriend(userId,friendId);

      //远程调用 => 维护用户表的粉丝|关注数量
      Result result1 =userClient.changeFollowCount(userId,-1);
      Result result2 = userClient.changeFansCount(friendId,-1);

      if (!result1.isFlag() || !result2.isFlag()) { //两个微服务其中一个或全部调用失败
         throw new RuntimeException("操作失败!");
      }
   }

}
